<?php


namespace app\msgapi\service;

use app\msgapi\model\{AuthGroup, AuthRule};
use app\utils\Arr;

class HsgroupService extends BaseService
{
    protected $limit; //每页默认数量
    public function __construct(AuthGroup $authGroup)
    {
        parent::__construct();
        $this->model = $authGroup;
        $this->limit = config('page.defaule_limit');
    }

    public function getLists()
    {
        $limit = input('limit')?:$this->limit;
        $list = $this->model->order('id')->paginate($limit)->toArray();
        return success_json('成功',$list);
    }

    public function getAllGroup()
    {
        $list = $this->model->order('id')->field('id,title')->select()->toArray();
        return success_json('成功',$list);
    }

    public function _delete($id, bool $force = false)
    {
        if ($id == 1) {
            return ajax_return(1,'超级管理组不可删除');
        }
        return parent::_delete($id, $force);
    }

    // 授权页面数据
    public function getAuthData($id)
    {
        // 选中数据
        $checked = $this->model->where('id',$id)->value('rules');
        $checked_rules_show = $this->model->where('id',$id)->value('rules_show');
        // 转为数组，方便下面使用，,'true' spread//定义都展开
        $data = AuthRule::field("id,title,pid,is_mobile")->where('state','1')->order('sort desc,id asc')->select()->toArray();
        $data = Arr::arrayToTree($data,'id','pid','children');// 子级数据装入父级中，children符合插件的键

        return success_json('成功',compact('id', 'data', 'checked','checked_rules_show'));
    }

    // 更新权限
    public function _updateAuthGroupRule()
    {
        $data = input('post.');
        $rules =  trim(str_replace('，',',',$data['rules']),', '); //去掉左右两边的空字符和英文逗号
        $rules_show = trim(str_replace('，',',',$data['rules_show']),', ');
        try{
            $this->model::update(['rules'=>$rules,'rules_show'=>$rules_show],['id'=>$data['id']]);
            return success_json('授权成功');
        } catch (\Exception $e){
            return error_json('授权失败，请重试');
        }
    }
}